package quik.article;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.oreilly.servlet.MultipartRequest;

import comm.util.QuikFileRenamePolicy;
import comm.util.QuikHashMap;
import comm.util.RequestManager;
import comm.util.SqlMapLoader;

public class ArticleProc {
	public ArticleProc() {
		// TODO Auto-generated constructor stub
	}
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	public String regArticle(HttpServletRequest request,String savePath) throws UnsupportedEncodingException{
		String result = "FAIL";
		String dataSeq = "";
		String articleSeq = "";
		QuikHashMap hm = new QuikHashMap();
		
		File f = new File(savePath);
		f.mkdir();
		System.out.println(savePath);
		int sizeLimit = 10 * 1024 * 1024 ; // 1메가까지 제한 넘어서면 예외발생
		QuikFileRenamePolicy renamePolicy = new QuikFileRenamePolicy();
		try{
			MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit,"UTF-8", renamePolicy );
		 	Enumeration formFileNames=multi.getFileNames();  // 폼의 이름 반환
		 	Enumeration formNames = multi.getParameterNames();
		 	
		 	String formFileName = (String)formFileNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
			String fileName = multi.getFilesystemName(formFileName); // 파일의 이름 얻기
			String formName = null;
			while(formNames.hasMoreElements()){
					formName = (String) formNames.nextElement();
					System.out.println(formName+"///////"+multi.getParameter(formName));
					hm.put(formName.toUpperCase(), multi.getParameter(formName).toString());
			}

		    if(fileName == null) { // 파일이 업로드 되지 않았을때
		    	result = "FAIL";
		    } else { // 파일이 업로드 되었을때
		    	int dot = fileName.lastIndexOf(".");
		    	String ext = "";
			    if (dot != -1) {
			    	ext = fileName.substring(dot+1);  // without "."
			    	ext = ext.toLowerCase();
			    }
			    hm.put("ORIGIN_FILE", renamePolicy.originName);
			    
			    if(ext.equals("jpg")||ext.equals("jpeg")||ext.equals("gif")||ext.equals("png")||ext.equals("bmp")){
			    	hm.put("DATA_TYPE",0); //DATA_TYPE = 0 이미지
			    }else{
			    	hm.put("DATA_TYPE", 1); //1은 그외 파일들
			    }
			    
	    		System.out.println("업로드 성공 :"+fileName);
		        fileName=new String(fileName);
		        hm.put("GROUP_SEQ",request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		        hm.put("MEMBER_SEQ",request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
		        hm.put("FILE", fileName);
		        result = hm.get("URL").toString(); 
		        
		        dataSeq = (String)sqlMapper.insert("article.regData",hm);
		        
		    } // end if
		    
		    if(hm.get("COMMENT")!=null && !hm.get("COMMENT").equals("http://")){
		    	//링크자료가 존재
		    	hm.put("DATA_TYPE", 2); //2는 링크
		    	hm.put("GROUP_SEQ",request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		        hm.put("MEMBER_SEQ",request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
		        dataSeq = (String)sqlMapper.insert("article.regData",hm);
		    }
		    
			} catch(Exception e) {
			    System.out.print("예외 상황 발생..! "+e.getMessage());
			    result = hm.get("URL").toString()+"&error=file";
			}
		
			hm.put("GROUP_SEQ", request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
			System.out.println("["+hm.get("ARTICLE_CONTENT")+"]");
			hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
			if(hm.get("INNERGROUP_SEQ")!=null && hm.get("INNERGROUP_SEQ").toString().length()<1){
				hm.remove("INNERGROUP_SEQ");
			}
			try {
				articleSeq = (String) sqlMapper.insert("article.regArticle",hm);
				if(articleSeq.length()>0 && dataSeq.length()>0){
					hm.put("ARTICLE_SEQ", articleSeq);
					hm.put("DATA_SEQ", dataSeq);
					sqlMapper.update("article.setDataArticle",hm);
				}
				
				
				result = hm.get("URL").toString()+"&success=1";
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return result;
	}
	
	
	
	public QuikHashMap getArticle(String articleSeq){
		QuikHashMap hm = new QuikHashMap();
		
		
		try {
			hm = (QuikHashMap) sqlMapper.queryForObject("article.getArticle",articleSeq);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return hm;
	}
	
	public ArrayList getArticleList(int pageNum,int pageSize,HttpServletRequest request){
		ArrayList lt = null;
		QuikHashMap hm = new QuikHashMap();
		
		if(pageNum>0){
			if(pageSize>0)
				hm.put("PAGE_START", (pageNum - 1) * pageSize);
			else
				hm.put("PAGE_START", (pageNum - 1) * 5);
		}else{
			hm.put("PAGE_START", 0);
		}
		if(pageSize>0){
			hm.put("PAGE_SIZE", pageSize);
		}else{
			hm.put("PAGE_SIZE", 5);
		}
		hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
		hm.put("GROUP_SEQ", request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		try {
			lt = (ArrayList) sqlMapper.queryForList("article.getArticleList",hm);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	
	public ArrayList getArticleSearchList(HttpServletRequest request) throws UnsupportedEncodingException{
		ArrayList lt = null;
		QuikHashMap hm = new QuikHashMap();
		hm.put("GROUP_SEQ", request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		hm.put("KEYWORD", "%"+request.getParameter("s")+"%");
		try {
			lt = (ArrayList) sqlMapper.queryForList("article.getArticleSearchList",hm);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	
	
	public ArrayList getArticleTotalList(int pageNum,int pageSize,HttpServletRequest request){
		ArrayList lt = null;
		QuikHashMap hm = new QuikHashMap();
		
		if(pageNum>0){
			if(pageSize>0)
				hm.put("PAGE_START", (pageNum - 1) * pageSize);
			else
				hm.put("PAGE_START", (pageNum - 1) * 5);
		}else{
			hm.put("PAGE_START", 0);
		}
		if(pageSize>0){
			hm.put("PAGE_SIZE", pageSize);
		}else{
			hm.put("PAGE_SIZE", 5);
		}
		
		hm.put("GROUP_SEQ", request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		try {
			lt = (ArrayList) sqlMapper.queryForList("article.getArticleTotalList",hm);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	
}
